<template>
  <div class="publish-container">
    <el-card class="publish-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><DocumentAdd /></el-icon>
          <span class="header-title">发布失物信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="publish-form"
      >
        <el-form-item label="物品标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入物品标题，如：捡到一部iPhone手机"
            maxlength="100"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="物品类别" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择物品类别"
            style="width: 100%"
          >
            <el-option label="电子产品" value="电子产品" />
            <el-option label="证件卡类" value="证件卡类" />
            <el-option label="书籍资料" value="书籍资料" />
            <el-option label="生活用品" value="生活用品" />
            <el-option label="钥匙" value="钥匙" />
            <el-option label="衣物饰品" value="衣物饰品" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="拾取地点" prop="location">
          <el-input
            v-model="form.location"
            placeholder="请输入拾取地点，如：图书馆三楼阅览室"
            maxlength="200"
            clearable
          />
        </el-form-item>

        <el-form-item label="拾取时间" prop="foundTime">
          <el-date-picker
            v-model="form.foundTime"
            type="datetime"
            placeholder="请选择拾取时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="物品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="6"
            placeholder="请详细描述物品的特征，帮助失主更快找到自己的物品"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="物品图片">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadAction"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :limit="6"
            :headers="uploadHeaders"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">
                支持jpg、png、gif格式，最多上传6张图片，每张不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            发布失物信息
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewImage" style="width: 100%" alt="预览图片" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentAdd, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { reqPublishLostItem } from '@/api/lost'
import useUserStore from '@/stores/modules/user'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  title: '',
  category: '',
  location: '',
  foundTime: '',
  description: '',
})

// 文件列表
const fileList = ref<UploadUserFile[]>([])

// 已上传的图片URL列表
const uploadedImages = ref<string[]>([])

// 加载状态
const loading = ref(false)

// 图片预览
const previewVisible = ref(false)
const previewImage = ref('')

// 上传地址
const uploadAction = computed(() => {
  return '/api/lost/upload/image'
})

// 上传请求头
const uploadHeaders = computed(() => {
  return {
    token: userStore.token || ''
  }
})

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入物品标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度为5-100个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择物品类别', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入拾取地点', trigger: 'blur' }
  ],
  foundTime: [
    { required: true, message: '请选择拾取时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入物品描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '描述长度为10-1000个字符', trigger: 'blur' }
  ]
})

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isImage = rawFile.type.startsWith('image/')
  const isLt5M = rawFile.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  if (response.code === 200) {
    uploadedImages.value.push(response.data.url)
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
    // 移除上传失败的文件
    const index = fileList.value.findIndex(file => file.uid === uploadFile.uid)
    if (index > -1) {
      fileList.value.splice(index, 1)
    }
  }
}

// 移除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const index = fileList.value.findIndex(file => file.uid === uploadFile.uid)
  if (index > -1) {
    uploadedImages.value.splice(index, 1)
  }
}

// 预览图片
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  previewImage.value = uploadFile.url!
  previewVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (uploadedImages.value.length === 0) {
        ElMessage.warning('请至少上传一张物品图片')
        return
      }

      loading.value = true
      try {
        // 构建FormData
        const formData = new FormData()
        formData.append('title', form.title)
        formData.append('category', form.category)
        formData.append('location', form.location)
        formData.append('foundTime', form.foundTime)
        formData.append('description', form.description)

        // 添加图片URL
        uploadedImages.value.forEach(url => {
          formData.append('images', url)
        })

        const result = await reqPublishLostItem(formData)

        if (result.code === 200) {
          ElMessage.success('发布成功')
          // 询问是否跳转到列表页
          ElMessageBox.confirm(
            '失物信息已发布成功，是否前往失物招领页查看？',
            '发布成功',
            {
              confirmButtonText: '前往查看',
              cancelButtonText: '继续发布',
              type: 'success',
            }
          )
            .then(() => {
              router.push('/receive')
            })
            .catch(() => {
              handleReset()
            })
        } else {
          ElMessage.error(result.message || '发布失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '发布失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  fileList.value = []
  uploadedImages.value = []
}
</script>

<style scoped lang="scss">
.publish-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.publish-card {
  :deep(.el-card__header) {
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;

  .header-icon {
    font-size: 24px;
  }

  .header-title {
    font-size: 18px;
    font-weight: 600;
  }
}

.publish-form {
  padding: 20px 0;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #333;
  }

  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
    border-radius: 8px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 120px;
    height: 120px;
    border-radius: 8px;
  }
}

.upload-tip {
  color: #999;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 8px;
}

// 响应式设计
@media (max-width: 768px) {
  .publish-container {
    padding: 10px;
  }

  .publish-form {
    :deep(.el-form-item__label) {
      width: 80px !important;
    }
  }
}
</style>
